 package com.yangguo.code.generator.util;

 import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.ResourceUtils;

 /***
  * mybaits 代码生成工具
  *
  * @author yangcheng6327
  *
  */
 public class MybatisGeneratorUtil {

     /**
      * <函数描述> 代码生成 ,MybatisGenerator配置文件在classpath下
      * 
      * @param name MybatisGenerator配置文件名
      */
     public static void generatorCodeOnClassPathConfigXml(String name) throws Exception {
         ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
         Resource[] resources = resolver.getResources("classpath:" + name);
         if (resources != null && resources.length > 0) {
             for (Resource resource : resources) {
                 if (resource.getFile().isFile() && resource.getFile().exists()) {
                     generator(resource.getFile().getPath());
                     break;
                 }
             }
         }

     }

     /**
      * <函数描述> 代码生成 ,指定MybatisGenerator配置文件的路径
      * 
      * @param path 资源文件的位置
      * @throws Exception
      */
     public static void generatorCodeOnConfigXmlPath(String path) throws Exception {
         generator(path);
     }

     /**
      * <函数描述>
      * 
      * @throws Exception
      */
     private static void generator(String path) throws Exception {
         List<String> warnings = new ArrayList<String>();
         boolean overwrite = true;
         File configFile = ResourceUtils.getFile(path);
         ConfigurationParser cp = new ConfigurationParser(warnings);

         Configuration config = cp.parseConfiguration(configFile);
         DefaultShellCallback callback = new DefaultShellCallback(overwrite);
         MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
         myBatisGenerator.generate(null);

         System.out.println("代码生成完毕>>>>>>>>>>>>");
     }

     public static void main(String[] args) throws Exception {
         MybatisGeneratorUtil.generatorCodeOnClassPathConfigXml("generatorConfig.xml");
     }

 }
